
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.db.models import Q, Count
from datetime import date, datetime, timedelta
from .models import CFUser, Submission, DailyStats
from .services import CFAnalyzer, update_all_active_users, update_user_history_data
from .serializers import (
    CFUserSerializer, SubmissionSerializer, DailyStatsSerializer,
    UpdateResultSerializer, BulkUpdateResultSerializer
)


@api_view(['GET'])
def api_root(request):
    """API 根端点，提供所有可用端点的链接"""
    return Response({
        'message': 'Codeforces 数据监控系统 API',
        'endpoints': {
            'users': {
                'list': request.build_absolute_uri('/api/cf/users/'),
                'detail': request.build_absolute_uri('/api/cf/users/{id}/'),
                'comparison': request.build_absolute_uri('/api/cf/users/comparison/'),
                'description': '用户管理'
            },
            'submissions': {
                'list': request.build_absolute_uri('/api/cf/submissions/'),
                'description': '提交记录查询'
            },
            'stats': {
                'daily': request.build_absolute_uri('/api/cf/stats/'),
                'weekly': request.build_absolute_uri('/api/cf/stats/weekly/'),
                'verdict_distribution': request.build_absolute_uri('/api/cf/stats/verdict-distribution/'),
                'difficulty_distribution': request.build_absolute_uri('/api/cf/stats/difficulty-distribution/'),
                'description': '统计数据查询'
            },
            'dashboard': {
                'summary': request.build_absolute_uri('/api/cf/dashboard/'),
                'description': '仪表板数据'
            },
            'update': {
                'today': request.build_absolute_uri('/api/cf/update/today/'),
                'history': request.build_absolute_uri('/api/cf/update/history/'),
                'status': request.build_absolute_uri('/api/cf/update/status/'),
                'description': '数据更新'
            },
            'documentation': {
                'url': request.build_absolute_uri('/api/docs/'),
                'description': 'API 文档'
            }
        }
    })

@api_view(['GET', 'POST'])
def cf_user_list(request):
    """CF用户列表API"""
    if request.method == 'GET':
        users = CFUser.objects.all()
        serializer = CFUserSerializer(users, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = CFUserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
def cf_user_detail(request, pk):
    """CF用户详情API"""
    try:
        user = CFUser.objects.get(pk=pk)
    except CFUser.DoesNotExist:
        return Response({'error': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = CFUserSerializer(user)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = CFUserSerializer(user, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        user.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


@api_view(['GET'])
def submission_list(request):
    """提交记录列表API"""
    submissions = Submission.objects.all()

    # 过滤参数
    user_id = request.GET.get('user_id')
    date_str = request.GET.get('date')
    verdict = request.GET.get('verdict')

    if user_id:
        submissions = submissions.filter(user_id=user_id)

    if date_str:
        try:
            date_obj = datetime.strptime(date_str, '%Y-%m-%d').date()
            submissions = submissions.filter(creation_time__date=date_obj)
        except ValueError:
            return Response({'error': '日期格式错误'}, status=status.HTTP_400_BAD_REQUEST)

    if verdict:
        submissions = submissions.filter(verdict=verdict)

    # 分页
    try:
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 20))
    except ValueError:
        return Response({'error': '分页参数格式错误'}, status=status.HTTP_400_BAD_REQUEST)

    start = (page - 1) * page_size
    end = start + page_size

    total_count = submissions.count()
    submissions_page = submissions.order_by('-creation_time')[start:end]

    serializer = SubmissionSerializer(submissions_page, many=True)

    return Response({
        'count': total_count,
        'page': page,
        'page_size': page_size,
        'total_pages': (total_count + page_size - 1) // page_size,
        'results': serializer.data
    })


@api_view(['GET'])
def daily_stats_list(request):
    """每日统计列表API"""
    stats = DailyStats.objects.all()

    # 过滤参数
    user_id = request.GET.get('user_id')
    start_date = request.GET.get('start_date')
    end_date = request.GET.get('end_date')

    if user_id:
        stats = stats.filter(user_id=user_id)

    if start_date:
        try:
            start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date()
            stats = stats.filter(date__gte=start_date_obj)
        except ValueError:
            return Response({'error': '开始日期格式错误'}, status=status.HTTP_400_BAD_REQUEST)

    if end_date:
        try:
            end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date()
            stats = stats.filter(date__lte=end_date_obj)
        except ValueError:
            return Response({'error': '结束日期格式错误'}, status=status.HTTP_400_BAD_REQUEST)

    stats = stats.order_by('-date')
    serializer = DailyStatsSerializer(stats, many=True)
    return Response(serializer.data)


@api_view(['POST'])
def update_today_data_api(request):
    """更新今日数据API"""
    user_id = request.data.get('user_id')

    if user_id:
        try:
            cf_user = CFUser.objects.get(id=user_id, is_active=True)
            analyzer = CFAnalyzer(cf_user)
            result = analyzer.update_today_data()
            serializer = UpdateResultSerializer(result)
            return Response(serializer.data)
        except CFUser.DoesNotExist:
            return Response(
                {'success': False, 'error': '用户不存在或未激活'},
                status=status.HTTP_404_NOT_FOUND
            )
    else:
        results = update_all_active_users()
        serializer = BulkUpdateResultSerializer({
            'success': True,
            'message': f'已更新 {len(results)} 个用户的数据',
            'results': results
        })
        return Response(serializer.data)


@api_view(['POST'])
def update_history_data_api(request):
    """更新历史数据API"""
    user_id = request.data.get('user_id')

    if not user_id:
        return Response(
            {'success': False, 'error': '请提供用户ID'},
            status=status.HTTP_400_BAD_REQUEST
        )

    result = update_user_history_data(user_id)
    serializer = UpdateResultSerializer(result)
    return Response(serializer.data)


@api_view(['GET'])
def dashboard_summary(request):
    """仪表板摘要数据API"""
    user_id = request.GET.get('user_id')
    view_type = request.GET.get('view_type', 'today')
    selected_date = request.GET.get('date')

    response_data = {
        'active_users': [],
        'selected_user': None,
        'today_stats': None,
        'today_submissions': [],
        'stats_dates': [],
        'date_submissions': [],
        'date_stats': None,
        # 添加兼容字段
        'submissions': [],
        'results': []
    }

    # 获取活跃用户列表
    active_users = CFUser.objects.filter(is_active=True)
    response_data['active_users'] = CFUserSerializer(active_users, many=True).data

    if user_id:
        try:
            selected_user = CFUser.objects.get(id=user_id, is_active=True)
            response_data['selected_user'] = CFUserSerializer(selected_user).data

            if view_type == 'today':
                # 今日数据
                today_stats = DailyStats.objects.filter(
                    user=selected_user,
                    date=date.today()
                ).first()

                if today_stats:
                    response_data['today_stats'] = DailyStatsSerializer(today_stats).data

                # 今日提交记录
                today_submissions = Submission.objects.filter(
                    user=selected_user,
                    creation_time__date=date.today()
                ).order_by('-creation_time')[:50]

                today_submissions_data = SubmissionSerializer(today_submissions, many=True).data
                response_data['today_submissions'] = today_submissions_data
                # 添加兼容字段
                response_data['submissions'] = today_submissions_data
                response_data['results'] = today_submissions_data

            elif view_type == 'history':
                # 历史统计数据日期列表
                stats_dates = DailyStats.objects.filter(user=selected_user).order_by('-date')
                response_data['stats_dates'] = DailyStatsSerializer(stats_dates, many=True).data

                # 特定日期的提交记录
                if selected_date:
                    try:
                        date_obj = datetime.strptime(selected_date, '%Y-%m-%d').date()
                        date_submissions = Submission.objects.filter(
                            user=selected_user,
                            creation_time__date=date_obj
                        ).order_by('-creation_time')

                        date_stats = DailyStats.objects.filter(
                            user=selected_user,
                            date=date_obj
                        ).first()

                        date_submissions_data = SubmissionSerializer(date_submissions, many=True).data
                        response_data['date_submissions'] = date_submissions_data
                        # 添加兼容字段
                        response_data['submissions'] = date_submissions_data
                        response_data['results'] = date_submissions_data

                        if date_stats:
                            response_data['date_stats'] = DailyStatsSerializer(date_stats).data

                    except ValueError:
                        response_data['error'] = '日期格式错误'

        except CFUser.DoesNotExist:
            response_data['error'] = '用户不存在或未激活'

    return Response(response_data)


# 在 cf/views.py 中添加以下接口

@api_view(['GET'])
def weekly_stats(request):
    """获取最近7天的统计数据"""
    user_id = request.GET.get('user_id')
    days = int(request.GET.get('days', 7))

    end_date = date.today()
    start_date = end_date - timedelta(days=days - 1)

    # 构建响应数据
    response_data = {
        'dates': [],
        'total_submissions': [],
        'accepted_submissions': [],
        'problems_solved': [],
        'acceptance_rates': []
    }

    # 生成日期列表
    current_date = start_date
    while current_date <= end_date:
        response_data['dates'].append(current_date.strftime('%m/%d'))
        current_date += timedelta(days=1)

    # 查询统计数据
    stats_query = DailyStats.objects.filter(
        date__gte=start_date,
        date__lte=end_date
    )

    if user_id:
        stats_query = stats_query.filter(user_id=user_id)

    stats_data = stats_query.order_by('date')

    # 按日期填充数据
    current_date = start_date
    for single_date in response_data['dates']:
        date_obj = datetime.strptime(single_date, '%m/%d').replace(year=end_date.year).date()

        # 查找对应日期的统计
        day_stats = stats_data.filter(date=date_obj).first()

        if day_stats:
            response_data['total_submissions'].append(day_stats.total_submissions)
            response_data['accepted_submissions'].append(day_stats.accepted_submissions)
            response_data['problems_solved'].append(day_stats.problems_solved)
            response_data['acceptance_rates'].append(
                round((day_stats.accepted_submissions / day_stats.total_submissions * 100), 2)
                if day_stats.total_submissions > 0 else 0
            )
        else:
            # 如果没有数据，填充0
            response_data['total_submissions'].append(0)
            response_data['accepted_submissions'].append(0)
            response_data['problems_solved'].append(0)
            response_data['acceptance_rates'].append(0)

    return Response(response_data)


# 在 cf/views.py 中添加

@api_view(['GET'])
def verdict_distribution(request):
    """获取提交结果分布统计"""
    user_id = request.GET.get('user_id')
    days = int(request.GET.get('days', 30))  # 默认统计最近30天

    start_date = date.today() - timedelta(days=days)

    # 构建查询
    submissions_query = Submission.objects.filter(
        creation_time__gte=start_date
    )

    if user_id:
        submissions_query = submissions_query.filter(user_id=user_id)

    # 统计各种结果的数量
    verdict_stats = submissions_query.values('verdict').annotate(
        count=Count('id')
    ).order_by('-count')

    # 格式化结果
    distribution_data = []
    for stat in verdict_stats:
        distribution_data.append({
            'name': stat['verdict'],
            'value': stat['count'],
            'formatted_name': format_verdict(stat['verdict'])
        })

    return Response({
        'distribution': distribution_data,
        'total': submissions_query.count(),
        'period': f'最近{days}天'
    })


def format_verdict(verdict):
    """格式化提交结果名称"""
    verdict_map = {
        'OK': 'AC',
        'ACCEPTED': 'AC',
        'WRONG_ANSWER': 'WA',
        'TIME_LIMIT_EXCEEDED': 'TLE',
        'MEMORY_LIMIT_EXCEEDED': 'MLE',
        'RUNTIME_ERROR': 'RE',
        'COMPILATION_ERROR': 'CE'
    }
    return verdict_map.get(verdict, verdict)


# 在 cf/views.py 中添加

@api_view(['GET'])
def problem_difficulty_distribution(request):
    """获取题目难度分布"""
    user_id = request.GET.get('user_id')

    submissions_query = Submission.objects.all()

    if user_id:
        submissions_query = submissions_query.filter(user_id=user_id)

    # 统计AC的题目按难度分布
    ac_submissions = submissions_query.filter(verdict='OK')

    # 提取题目难度信息（假设tags中包含难度信息）
    difficulty_stats = {}

    for submission in ac_submissions:
        tags = submission.get_tags_list()
        # 查找难度标签
        difficulty = None
        for tag in tags:
            if any(diff in tag.upper() for diff in ['HARD', 'MEDIUM', 'EASY', '*', '1', '2', '3', '4', '5']):
                difficulty = tag
                break

        if not difficulty:
            difficulty = '未知'

        difficulty_stats[difficulty] = difficulty_stats.get(difficulty, 0) + 1

    # 格式化数据
    distribution_data = [{'name': k, 'value': v} for k, v in difficulty_stats.items()]

    return Response({
        'distribution': distribution_data,
        'total_solved': ac_submissions.values('contest_id', 'problem_index').distinct().count()
    })


# 在 cf/views.py 中添加

@api_view(['GET'])
def user_comparison(request):
    """获取用户对比数据"""
    active_users = CFUser.objects.filter(is_active=True)

    comparison_data = []

    for user in active_users:
        # 获取用户总统计
        total_stats = {
            'total_submissions': Submission.objects.filter(user=user).count(),
            'accepted_submissions': Submission.objects.filter(user=user, verdict='OK').count(),
            'problems_solved': Submission.objects.filter(user=user, verdict='OK')
            .values('contest_id', 'problem_index').distinct().count(),
        }

        # 计算通过率
        acceptance_rate = round(
            (total_stats['accepted_submissions'] / total_stats['total_submissions'] * 100), 2
        ) if total_stats['total_submissions'] > 0 else 0

        # 获取最近活跃时间
        last_submission = Submission.objects.filter(user=user).order_by('-creation_time').first()
        last_active = last_submission.creation_time if last_submission else user.created_at

        comparison_data.append({
            'user_id': user.id,
            'username': user.username,
            'handle': user.handle,
            'total_submissions': total_stats['total_submissions'],
            'accepted_submissions': total_stats['accepted_submissions'],
            'problems_solved': total_stats['problems_solved'],
            'acceptance_rate': acceptance_rate,
            'last_active': last_active,
            'is_active': user.is_active
        })

    return Response(comparison_data)


# 在 cf/views.py 中添加

@api_view(['GET'])
def update_status(request):
    """获取数据更新状态"""
    active_users = CFUser.objects.filter(is_active=True)

    status_data = {
        'last_updated': None,
        'user_status': [],
        'overall_status': {
            'total_users': active_users.count(),
            'users_updated_today': 0,
            'total_submissions_today': 0
        }
    }

    today = date.today()

    for user in active_users:
        # 获取用户今日统计
        today_stats = DailyStats.objects.filter(user=user, date=today).first()

        user_status = {
            'user_id': user.id,
            'username': user.username,
            'handle': user.handle,
            'last_updated': user.last_updated,
            'today_submissions': today_stats.total_submissions if today_stats else 0,
            'today_solved': today_stats.problems_solved if today_stats else 0,
            'is_updated_today': today_stats is not None
        }

        status_data['user_status'].append(user_status)

        # 更新总体状态
        if today_stats:
            status_data['overall_status']['users_updated_today'] += 1
            status_data['overall_status']['total_submissions_today'] += today_stats.total_submissions

    # 设置最后更新时间
    if status_data['user_status']:
        status_data['last_updated'] = max(
            [user['last_updated'] for user in status_data['user_status']]
        )

    return Response(status_data)

